package com.education.platform.api.service.impl;

import com.education.platform.api.config.ThreadUser;
import com.education.platform.api.service.AccountFlowService;

import com.education.platform.api.vo.request.UserOrderUpdateVO;
import com.education.platform.common.enums.*;
import com.education.platform.common.exception.AssertException;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.util.BeanUtil;
import com.education.platform.common.util.OrderNoGenerator;
import com.education.platform.common.util.UUIDGenerator;
import com.education.platform.common.web.ResponseCode;
import com.education.platform.dao.*;
import com.education.platform.dao.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.education.platform.common.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import com.education.platform.api.service.UserOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
* describe: 订单
* @author : tomato
* @date: 2020-06-14 09:47:11.640
**/
@Service
public class UserOrderServiceImpl extends BaseServiceImpl<UserOrderDao, UserOrderDO> implements UserOrderService {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserOrderServiceImpl.class);

    @Autowired
	private UserOrderDao userOrderDao;
    @Autowired
    private OrderReceiptDao orderReceiptDao;

    @Autowired
    private ReceiptAddressDao receiptAddressDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private AccountFlowDao accountFlowDao;

    @Autowired
    private AccountFlowService accountFlowService;

    /**
     * 创建订单
     * @param updateVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserOrderDO createOrder(UserOrderUpdateVO updateVO) {
        this.checkOrder(updateVO);
        GoodsDO goodsDO= goodsDao.getById(updateVO.getGoodsId());
        UserOrderDO userOrder = BeanUtil.convert(updateVO, UserOrderDO.class);
        userOrder.setUserId(ThreadUser.getUserId());
        userOrder.setUserName(ThreadUser.getUserName());
        userOrder.setOrderNo(OrderNoGenerator.generator());
        userOrder.setOrderStatus(OrderStatusEnum.WAIT_PAY.getValue());
        userOrder.setOrderStatusName(OrderStatusEnum.WAIT_PAY.getDes());
        userOrder.setCreateTime(new Date());
        userOrder.setOrderType(OrderTypeEnum.OBJECT_ORDER.getValue());
        userOrder.setOrderTypeName(OrderTypeEnum.OBJECT_ORDER.getDes());
        userOrder.setCoverImage(goodsDO.getCoverImage());
        userOrder.setGoodsId(goodsDO.getId());
        userOrder.setGoodsName(goodsDO.getGoodsName());
        userOrder.setDeleted(false);
        if(userOrderDao.insert(userOrder)==1){
            //新增订单关联的收货地址信息
            OrderReceiptDO orderReceiptDTO = new OrderReceiptDO();
            orderReceiptDTO.setOrderId(userOrder.getId());
            orderReceiptDTO.setOrderNo(userOrder.getOrderNo());
            orderReceiptDTO.setCreateTime(new Date());
            orderReceiptDTO.setReceiptName(updateVO.getReceiptName());
            orderReceiptDTO.setReceiptPhone(updateVO.getReceiptPhone());
            orderReceiptDTO.setDetailAddress(updateVO.getReceiptDetailAddress());
            orderReceiptDTO.setDeleted(false);
            orderReceiptDao.insert(orderReceiptDTO);

            //修改用户收货地址表。
            ReceiptAddressDO addressDO  = receiptAddressDao.getByUserId(ThreadUser.getUserId());
            ReceiptAddressDO addressDOUpdate = new ReceiptAddressDO();
            addressDOUpdate.setReceiptName(updateVO.getReceiptName());
            addressDOUpdate.setReceiptPhone(updateVO.getReceiptPhone());
            addressDOUpdate.setDetailAddress(updateVO.getReceiptDetailAddress());
            if(addressDO == null){
                addressDOUpdate.setCreateTime(new Date());
                addressDOUpdate.setUserId(ThreadUser.getUserId());
                receiptAddressDao.insert(addressDOUpdate);
            }else{
                addressDOUpdate.setUpdateTime(new Date());
                addressDOUpdate.setId(addressDO.getId());
                receiptAddressDao.updateById(addressDOUpdate);
            }

        }
        return userOrder;
    }



    /**
     * 确认支付商品订单
     *
     * @param orderId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmPay(Integer orderId) {
        if(orderId == null){
            AssertException.throwBusinessEp("订单id为空");
        }
        UserOrderDO orderDO = userOrderDao.getById(orderId);
        if(orderDO == null){
            AssertException.throwBusinessEp("订单不存在");
        }
        AccountDO accountDO = this.checkAccount(orderDO.getTotalPrice());
        AccountDO accountUpdate = new AccountDO();
        accountUpdate.setId(accountDO.getId());
        accountUpdate.setBeanNumber(accountDO.getBeanNumber()-orderDO.getTotalPrice());
        accountUpdate.setUpdateTime(new Date());
        if( accountDao.updateById(accountUpdate)==1){
            //修改订单状态
            UserOrderDO orderDOUpdate  = new UserOrderDO();
            orderDOUpdate.setId(orderDO.getId());
            orderDOUpdate.setOrderStatus(OrderStatusEnum.WAIT_DELIVER.getValue());
            orderDOUpdate.setOrderStatusName(OrderStatusEnum.WAIT_DELIVER.getDes());
            if(userOrderDao.updateById(orderDOUpdate)==1){
                //增加商品销售量
                goodsDao.incSalesNum(orderDO.getNumber(), orderDO.getGoodsId());

                //插入流水记录
                accountFlowService.createAccountFlow(accountDO,FlowBusinessTypeEnum.BUY_GOODS,FlowTypeEnum.OUT,orderDO.getTotalPrice(),orderDO.getOrderNo());
                return true;
            }else {
                AssertException.throwBusinessEp("支付失败");
                return false;
            }

        }else{
            AssertException.throwBusinessEp("支付失败");
            return false;
        }
    }

    /**
     * 检查账户
     * @param totalPrice
     */
    private AccountDO checkAccount(int totalPrice){
        //检查历史豆是否足够
        AccountDO accountDO = accountDao.getByUserId(ThreadUser.getUserId());
        if(accountDO == null||accountDO.getBeanNumber()==null){
            AssertException.throwBusinessEp("账户异常");
        }
        if(accountDO.getBeanNumber()<totalPrice){
            throw new BusinessException("账户历史豆不足！", ResponseCode.NOT_ENOUGH.getCode());
        }
        return accountDO;
    }

    /**
     * 检查提价订单
     * @param updateVO
     */
    private void checkOrder(UserOrderUpdateVO updateVO){
        Integer goodsId = updateVO.getGoodsId();
        if(goodsId == null){
            AssertException.throwBusinessEp("商品id为null");
        }
        GoodsDO goodsDO= goodsDao.getById(goodsId);
        if(goodsDO == null){
            AssertException.throwBusinessEp("商品不存在");
        }
        if(updateVO.getNumber()==null||updateVO.getNumber()<=0){
            AssertException.throwBusinessEp("商品数量应大于0");
        }
        if(goodsDO.getCostBean()==null||goodsDO.getCostBean()<0){
            AssertException.throwBusinessEp("商品数据异常");
        }
        //设置单价和总价
        updateVO.setUnitPrice(goodsDO.getCostBean());
        updateVO.setTotalPrice(goodsDO.getCostBean()*updateVO.getNumber());
        //检查账户
        this.checkAccount(updateVO.getTotalPrice());
    }


    /**
     * 获取已经支付的订单
     *
     * @param userOrder
     * @return
     */
    @Override
    public List<UserOrderDO> getAreadyPayOrderList(UserOrderDO userOrder) {
        return userOrderDao.getAreadyPayOrderList(userOrder);
    }
}
